<template>
  <div>
    <template v-if="selectModel">
      <el-tree
        class="mt-2"
        ref="tree"
        :data="treeList"
        show-checkbox
        node-key="id"
        @check="getCurrentNode"
        :default-checked-keys="selectModelKeysNew"
        :props="treeProps"
      >
      </el-tree>
    </template>
    <template v-else>
      <div>
        <el-card class="box-card">
          <template v-slot:header>
            <div class="clearfix">
              <div class="container">
                <el-form inline size="small">
                  <el-form-item label="状态：">
                    <el-select v-model="listPram.status" placeholder="状态"  style="width: 270px" size="small" @change="handlerGetList()">
                      <el-option label="全部" :value="-1"></el-option>
                      <el-option label="显示" :value="1"></el-option>
                      <el-option label="不显示" :value="0"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="名称：">
                    <el-input v-model="listPram.name" placeholder="请输入名称"  style="width: 270px" size="small" clearable/>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" size="small" @click="handlerGetList()">查询</el-button>
                    <el-button size="small" type="primary" @click="handleAddMenu({ id: 0, name: '顶层目录' })">新增{{ biztype.name }}</el-button>
                  </el-form-item>
                </el-form>
              </div>
              
            </div>
          </template>
          
          <el-table
            :data="treeList"
            size="small"
            class="table"
            highlight-current-row
            row-key="id"
            :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
          >
            <el-table-column prop="name" label="名称" min-width="240">
              <template #default="{row}"> {{ row.name }} | {{ row.id }} </template>
            </el-table-column>
            <template v-if="!selectModel">
              <el-table-column label="类型" min-width="150">
                <template #default="{row}"> 
                  <span>{{ filterCategroyTypeHandle(filterEmptyHandle(row.type))}}</span> 
                </template>
              </el-table-column>
              <el-table-column label="分类图标" min-width="80">
                <template #default="{row}">
                  <div class="listPic" v-if="biztype.value === 5">
                    <i :class="'el-icon-' + row.extra" style="font-size: 20px" />
                  </div>
                  <div class="demo-image__preview" v-else>
                    <el-image
                      style="width: 36px; height: 36px"
                      :src="row.extra"
                      :preview-src-list="[row.extra]"
                      v-if="row.extra"
                    />
                    <img style="width: 36px; height: 36px" v-else :src="defaultImg" alt="" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="Url" min-width="250" v-if="biztype.value  === 5" key="2">
                <template #default="{row}">
                  <span>{{ row.url }}</span>
                </template>
              </el-table-column>
              <el-table-column label="排序" prop="sort" min-width="150" />
              <el-table-column label="状态" min-width="150">
                <!--  -->
                <template #default="{row}">
                  <el-switch
                    v-model="row.status"
                    :active-value="true"
                    :inactive-value="false"
                    active-text="显示"
                    inactive-text="隐藏"
                    @change="onchangeIsShow(row)"
                  />
                </template>
              </el-table-column>

              <el-table-column label="操作" min-width="200" fixed="right">
                <template #default="{row}">
                  <el-button
                    v-if="(biztype.value === 1 && row.pid === 0) || biztype.value === 5"
                    type="primary" text
                    size="small"
                    @click="handleAddMenu(row)"
                    >添加子目录</el-button>
                  <el-button
                    type="primary" text
                    size="small"
                    @click="handleEditMenu(row)"
                    >编辑</el-button>
                  <el-button
                    type="primary" text
                    size="small"
                    @click="handleDelMenu(row)"
                    >删除</el-button>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </el-card>
      </div>
    </template>
    <el-dialog
      :title="editDialogConfig.isCreate === 0 ? `创建${biztype.name}` : `编辑${biztype.name}`"
      v-model="editDialogConfig.visible"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <edit
        v-if="editDialogConfig.visible"
        :prent="editDialogConfig.prent"
        :is-create="editDialogConfig.isCreate"
        :edit-data="editDialogConfig.data"
        :biztype="editDialogConfig.biztype"
        :all-tree-list="treeList"
        @hideEditDialog="hideEditDialog"
      />
    </el-dialog>
  </div>
</template>

<script  lang="ts" setup>
import { ref,reactive,onMounted,getCurrentInstance} from 'vue'
import { ElTree } from 'element-plus'
import * as categoryApi from '@/api/shopping/categoryApi.js';
import * as selfUtil from '@/utils/ZBKJIutil.js';
import { filterCategroyType, filterEmpty } from '@/utils';
import info from './components/Category/info.vue';
// import edit from 'edit.vue';

interface Tree {
  id: number,
  label: string
  children?: Tree[]
}

const emit = defineEmits(['rulesSelect'])
const { appContext } = getCurrentInstance() as ComponentInternalInstance
const biztype = reactive({'name': '', 'value': 1})// 类型，1 产品分类，2 附件分类，3 文章分类， 4 设置分类， 5 菜单分类
const tree = ref<InstanceType<typeof ElTree>>();
const pid = ref({
  type: Number,
  default: 0,
  validator: (value:any) => {
    return value >= 0;
  },
});
const selectModel = ref(false);
const selectModelKeys = reactive([])
const rowSelect= reactive({})
const selectModelKeysNew = reactive(selectModelKeys)
const loadingX = ref(false)
const constants= reactive(appContext.config.globalProperties.$constants);
const treeProps= reactive({
  label: 'name',
  children: 'child',
  // expandTrigger: 'hover',
  // checkStrictly: false,
  // emitPath: false
})
const treeCheckedKeys = ref([])// 选择模式下的属性结构默认选中
const multipleSelection = ref([])
const editDialogConfig = reactive({
  visible: false,
  isCreate: 0, // 0=创建，1=编辑
  prent: {}, // 父级对象
  data: {},
  biztype: biztype, // 统一主业务中的目录类型
  type:0
})
const treeList = ref<Tree[]>([]);

const listPram = reactive({
  pid: pid,
  type: biztype.value,
  status: -1,
  name: '',
  page: constants.page.page,
  limit: constants.page.limit[0],
})
const viewInfoConfig = reactive({
  data: 0,
  visible: false,
})
const defaultImg = ref('@/assets/imgs/moren.jpg')

const filterEmptyHandle = (value:any) =>{ 
  return filterEmpty(value);
}
    
const filterCategroyTypeHandle = (value:any) =>{ 
  return filterCategroyType(value);
}
const onchangeIsShow = (row:any) =>{
  categoryApi
    .categroyUpdateStatus(row.id)
    .then(() => {
      ElMessage.success('修改成功');
      handlerGetTreeList();
    })
    .catch(() => {
      row.status = !row.status;
    });
}
const handleEditMenu = (rowData:any)=>{
  editDialogConfig.isCreate = 1;
  editDialogConfig.data = rowData;
  editDialogConfig.prent = rowData;
  editDialogConfig.visible = true;
}
const handleAddMenu = (rowData:any)=>{
  console.log(rowData);
  editDialogConfig.isCreate = 0;
  editDialogConfig.prent = rowData;
  editDialogConfig.data = {};
  editDialogConfig.biztype = biztype;
  editDialogConfig.visible = true;
}
const getCurrentNode = (data:any)=>{
  let node = tree.value!.getNode(data);
childNodes(node);
// parentNodes(node);
//是否编辑的表示
// ruleForm.isEditorFlag = true;
//编辑时候使用
emit('rulesSelect', tree.value!.getCheckedKeys());
// selectModelKeys = $refs.tree.getCheckedKeys();
//无论编辑和新增点击了就传到后台这个值
// $emit('rulesSelect', $refs.tree.getCheckedKeys().concat($refs.tree.getHalfCheckedKeys()));
// ruleForm.menuIdsisEditor = $refs.tree.getCheckedKeys().concat($refs.tree.getHalfCheckedKeys());
}
//具体方法可以看element官网api
const childNodes = (node:any)=>{
  let len = node.childNodes.length;
  for (let i = 0; i < len; i++) {
    node.childNodes[i].checked = node.checked;
    childNodes(node.childNodes[i]);
  }
}
const parentNodes = (node:any)=>{
  if (node.parent) {
    for (let key in node) {
      if (key == 'parent') {
        node[key].checked = true;
        parentNodes(node[key]);
      }
    }
  }
}
const handleDelMenu = (rowData:any)=>{
  appContext.config.globalProperties.$modalSure('删除当前数据?').then(() => {
    categoryApi.deleteCategroy(rowData).then((data) => {
      handlerGetTreeList();
      ElMessage.success('删除成功');
    });
  });
}
const handlerGetList = ()=>{
  handlerGetTreeList();
  categoryApi.listCategroy({ status: listPram.status, type: 1 }).then(res => {
    treeList.value = res.data.list
  })
}
const handlerGetTreeList = ()=>{
  const _pram = { type: biztype.value, status: listPram.status, name: listPram.name };
  biztype.value !== 3
    ? categoryApi
        .treeCategroy(_pram)
      .then((res) => {
        console.log('请求树数据返回!== 3');
        treeList.value = handleAddArrt(res.data);
        console.log(treeList);
        })
        .catch(() => {
        })
    : categoryApi
        .listCategroy({ type: 3, status: listPram.status, pid: listPram.pid, name: listPram.name })
      .then((res) => {
        console.log('请求树数据返回== 3');
          treeList.value = res.data.list;
        });
}
const handlerGetInfo = (id:number)=>{
  viewInfoConfig.data = id;
  viewInfoConfig.visible = true;
}
const handleNodeClick = (data:any)=>{
  console.log('data:', data);
}
const handleAddArrt = (treeData:any)=>{
  const _result = selfUtil.addTreeListLabel(treeData);
  return _result;
}
const hideEditDialog = ()=>{
  setTimeout(() => {
    editDialogConfig.prent = {};
    editDialogConfig.type = 0;
    editDialogConfig.visible = false;
    handlerGetTreeList();
  }, 200);
}


onMounted(() => {
  console.log('进入onMounted');
  handlerGetTreeList();
})
  
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
